package com.cn.hu.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cn.hu.entity.Customer;
import com.cn.hu.entity.CustomerContacts;
import com.cn.hu.entity.CustomerDepartment;
import com.cn.hu.entity.Department;
import com.cn.hu.entity.Employee;
import com.cn.hu.entity.Plan;
import com.cn.hu.entity.User;
import com.cn.hu.entity.vo.ErrorCode;
import com.cn.hu.entity.vo.Result;
import com.cn.hu.entity.vo.SelectResult;
import com.cn.hu.service.WebService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
@RequestMapping("/web")
public class WebController {

	@Autowired
	WebService webService;

	private Result<Plan, String> res = new Result<>();

	private static Logger log = Logger.getLogger(WebController.class);

	/**
	 * 到登录页面
	 * @return
	 */
	@RequestMapping(value="/login.htm",method={RequestMethod.GET})
	public String login(HttpServletRequest req){
		String path;
		User user = (User)req.getSession().getAttribute("user");
		if(user==null){
			path="admin/login";
		}else{
			//这里根据user获取权限加载菜单
			//System.out.println("dddd"+user.getUserRuleRefs().isEmpty());
			path="redirect:index.htm";
		}
		return path;
	}

	/**
	 * 用户登录动作
	 * @param username
	 * @param password
	 * @param vCode
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/doLogin.htm",method={RequestMethod.POST})
	@ResponseBody
	public int initMethod(@NotNull String username,@NotNull String password,@NotNull String vCode,HttpServletRequest req){
		int res=0;
		Object obj = req.getSession().getAttribute("code");
		if(obj!=null){
			String code=obj.toString();
			if(code.equalsIgnoreCase(vCode)){
				//先验证是否存在账号
				User user=webService.findUserByAccount(username);
				if(user==null){
					System.out.println("账号密码错误");
					res=-1;
				}else{
					String pwd = user.getPassword();
					if(password.hashCode()==pwd.hashCode()){
						user.setPassword("");
						req.getSession().setAttribute("user", user);
						res=1;
						//查询并存储用户的权限

					}else{
						System.out.println("输入密码有误");
						res=-2;
					}
				}
			}else{
				System.out.println("验证码错误");
				res=-3;
			}
		}
		//每次都通过验证
		res=1;
		return res;
	}

	/**
	 * 到首页方法
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/index.htm",method={RequestMethod.GET})
	public String goAdminIndex(HttpServletRequest req){
		String path;
		User user = (User)req.getSession().getAttribute("user");
		if(user==null){
			path="redirect:login.htm";
		}else{
			//这里根据user获取权限加载菜单
			//System.out.println("dddd"+user.getUserRuleRefs().isEmpty());
			path="admin/index";
		}
		return path;
	}


	/**
	 * 退出系统方法
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/loginOut.htm",method={RequestMethod.GET})
	public String outLogin(HttpServletRequest req){
		String str="admin/login";
		req.getSession().setAttribute("user", null);
		return str;
	}



	/**
	 * 跳转到添加计划页面
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/goAddPlan.htm",method={RequestMethod.GET})
	public String goAddPlan(HttpServletRequest req){
		String str="admin/addPlan";
		return str;
	}

	/**
	 * 保存计划
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/savePlan.htm",method={RequestMethod.POST})
	@ResponseBody
	public String savePlan(HttpServletRequest req){
		String str="admin/addPlan";
		return str;
	}



	/**
	 * 前往计划列表页面
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/goPlanList.htm",method={RequestMethod.GET})
	public String goPlanList(HttpServletRequest req){
		String str="admin/planList";
		return str;
	}

	/**
	 * 读取计划列表
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/loadPlanList.htm",method={RequestMethod.POST})
	@ResponseBody
	public String loadPlanList(HttpServletRequest req){
		String str="redirect:index.htm";

		return str;
	}


	/**
	 * 前往合同列表页面
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/goContractList.htm",method={RequestMethod.GET})
	public String goContractList(HttpServletRequest req){
		return "admin/contractList";
	}

	/**
	 * 读取合同列表
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/loadContractList.htm",method={RequestMethod.POST})
	@ResponseBody
	public String loadContractList(HttpServletRequest req){
		String str="redirect:index.htm";

		return str;
	}



	/**
	 * 前往更新密码页面
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/goUpdatePwd.htm",method={RequestMethod.GET})
	public String goUpdatePwd(HttpServletRequest req){
		return "admin/updatePwd";
	}

	/**
	 * 更新密码方法
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/updatePwd.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<String, String> updatePwd(
			@RequestParam(value="oldPassword",required=true) String oldPassword,
			@RequestParam(value="newPassword",required=true) String newPassword,
			@RequestParam(value="rePassword",required=true) String rePassword,
			HttpServletRequest req
			){
		Result<String, String> res=new Result<>();
		boolean isRight =false;
		//验证两次密码是否一致
		if(newPassword.equals(rePassword)){
			//验证原始密码是否正确
			User user =(User)req.getSession().getAttribute("user");
			if(user!=null){
				User u = webService.findUserByAccount(user.getAccount());
				if(u!=null){
					if(oldPassword.equals(u.getPassword())){
						//更新密码
						u.setPassword(newPassword);
						isRight=webService.saveOrUpdateUser(u);
						res.setSuccess(isRight);
						if(isRight){
							res.setErrorCode(ErrorCode.success);
							res.setMessage("更新密码成功");
						}else{
							res.setSuccess(false);
							res.setErrorCode(1);
							res.setMessage("更新密码失败");
						}
					}else{
						res.setSuccess(false);
						res.setErrorCode(1);
						res.setMessage("原密码输入错误，请重新输入");
					}
				}else{
					res.setSuccess(false);
					res.setErrorCode(ErrorCode.unKnownError);
					res.setMessage(ErrorCode.unKnownErrorMessage);
				}
			}else{
				res.setSuccess(false);
				res.setErrorCode(ErrorCode.loginTimeOut);
				res.setMessage(ErrorCode.loginTimeOutMessage);
			}
		}
		return res;
	}


	/**
	 * 跳转到员工列表页面
	 * @return
	 */
	@RequestMapping(value="/goEmployeeList.htm",method={RequestMethod.GET})
	public String goEmployeeList(HttpServletRequest req){
		//读取员工部门列表并request
		List<Department> departmentList=webService.findAllDepartment();
		req.setAttribute("depList", departmentList);
		return "admin/employeeList";
	}

	/**
	 * 获取员工列表数据
	 * @param res
	 * @return
	 */
	@RequestMapping(value="/loadEmployeeList.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<Employee, String> loadEmployeeList(Result<Employee, String> res,Employee employee){
		if(res==null){
			res=new Result<>();
		}else{
			res=webService.loadEmployeeList(res,employee);
		}

		return res;
	}

	/**
	 * 新增或更新员工信息
	 * @param e
	 * @return
	 */
	@RequestMapping(value="/saveOrUpdateEmployee.htm",method={RequestMethod.POST})
	@ResponseBody
	public boolean saveOrUpdateEmployee(Employee e){
		boolean success=false;
		success=webService.saveOrUpdateEmployee(e);
		return success;
	}

	/**
	 * 删除员工，其实只是更新状态不可用
	 * @param delId
	 * @return
	 */
	@RequestMapping(value="/delEmployee.htm",method={RequestMethod.POST})
	@ResponseBody
	public boolean delEmployee(Integer delId){
		boolean success=false;
		success=webService.deleteEmployeeById(delId);
		return success;
	}

	/**
	 * 跳转到客户管理列表
	 * @return
	 */
	@RequestMapping(value="/goCustomerList.htm",method={RequestMethod.GET})
	public String goCustomerList(){
		return "admin/customerList";
	}

	/**
	 * 查询客户列表
	 * @param res
	 * @param customer
	 * @return
	 */
	@RequestMapping(value="/loadCustomerList.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<Customer, String> loadCustomerList(Result<Customer, String> res,Customer customer){
		if(res==null){
			res=new Result<>();
		}else{
			res=webService.loadCustomerList(res,customer);
		}

		return res;
	}

	/**
	 * 新增或更新客户
	 * @param customer
	 * @return
	 */
	@RequestMapping(value="/saveOrUpdateCustomer.htm",method={RequestMethod.POST})
	@ResponseBody
	public boolean saveOrUpdateCustomer(Customer customer){
		boolean success=false;
		success=webService.saveOrUpdateCustomer(customer);
		return success;
	}


	/**
	 * 删除客户，伪删除
	 * @param customer
	 * @return
	 */
	@RequestMapping(value="/delCustomer.htm",method={RequestMethod.POST})
	@ResponseBody
	public boolean delCustomer(int delId){
		boolean success=false;
		success=webService.deleteCustomer(delId);
		return success;
	}


	/**
	 * 跳转到客户联系人列表
	 * @param id
	 * @param name
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/goCustomerContactsList.htm",method={RequestMethod.GET})
	public String goCustomerContactsList(int id,String name,HttpServletRequest req) throws UnsupportedEncodingException{
		req.setAttribute("id", id);
		String str=URLDecoder.decode(name, "UTF-8");
		req.setAttribute("name", str);
		return "admin/customerContactsList";
	}

	/**
	 * 读取客户对应联系人列表
	 * @param res
	 * @param contacts
	 * @return
	 */
	@RequestMapping(value="/loadCustomerContactsList.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<CustomerContacts, String> loadCustomerContactsList(Result<CustomerContacts, String> res,CustomerContacts contacts,Integer customerId){
		if(res==null||customerId==null){
			res=new Result<>();
		}else{
			res=webService.loadCustomerContactsList(res,contacts,customerId);
		}

		return res;
	}


	/**
	 * 跳转到权限列表
	 * @param id
	 * @param name
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/goRuleList.htm",method={RequestMethod.GET})
	public String goRuleList(int id,String name,HttpServletRequest req) throws UnsupportedEncodingException{
		req.setAttribute("id", id);
		String str=URLDecoder.decode(name, "UTF-8");
		req.setAttribute("name", str);
		return "admin/customerContactsList";
	}


	/**
	 * 读取excel文件并返回展示
	 * 返回的时候不知道如何利用datatable接受，只能存session然后让datatable再请求一次
	 * 
	 * @param request
	 * @param response
	 * @param excelFile
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	/*@RequestMapping(value="/showExcelHandler.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<Plan, String> showExcelHandler(MultipartHttpServletRequest  request, HttpServletResponse response,@RequestParam("excelFile")MultipartFile excelFile) throws UnsupportedEncodingException{
		//判断文件类型，如果文件类型符合则继续；
		//FileMeta fileMeta = null;
		Result<Plan, String> res = new Result<>();
		// 可以在上传文件的同时接收其它参数
		System.out.println("收到用户[]的文件上传请求");
		if (excelFile.isEmpty()) {
			System.out.println("the excel file is empty !");
			res.setSuccess(false);
			res.setMessage("excel为空！请审核后重新执行上传操作");
		} else {
			String fileName=excelFile.getOriginalFilename();//获得文件名
			String fileType=fileName.substring(fileName.lastIndexOf(".")+1);//获得excel文件后缀

			//判断格式是否符合要求
			if(fileType.equalsIgnoreCase("xls")||fileType.equalsIgnoreCase("xlsx")){
				System.out.println("文件原名: " + fileName);
				System.out.println("文件名称: " + excelFile.getName());
				System.out.println("文件长度: " + excelFile.getSize()/1024+" Kb");
				System.out.println("文件类型: " + excelFile.getContentType());
				System.out.println("========================================");
				int excelType=-1;
				if(fileType.equalsIgnoreCase("xls")){
					excelType=0;
				}else{
					excelType=1;
				}
				try {
					InputStream stream=excelFile.getInputStream();
					res=webService.loadExcelToList(stream,excelType);
					request.setAttribute("res",res);
					this.res=res;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					res.setSuccess(false);
					res.setMessage("读取excel文件io流异常");
				}
			}else{
				res.setSuccess(false);
				res.setMessage("excel格式错误！请按照要求上传xls,xlsx为后缀的excel文件！");
			}


		}
		return res;
	}*/

	@RequestMapping(value="/showExcelHandler.htm",method={RequestMethod.POST})
	public String showExcelHandler(MultipartHttpServletRequest  request, HttpServletResponse response,@RequestParam("excelFile")MultipartFile excelFile) throws UnsupportedEncodingException{
		//判断文件类型，如果文件类型符合则继续；
		//FileMeta fileMeta = null;
		Result<Plan, String> res = new Result<>();
		// 可以在上传文件的同时接收其它参数
		System.out.println("收到用户[]的文件上传请求");
		if (excelFile.isEmpty()) {
			System.out.println("the excel file is empty !");
			res.setSuccess(false);
			res.setMessage("excel为空！请审核后重新执行上传操作");
		} else {
			String fileName=excelFile.getOriginalFilename();//获得文件名
			String fileType=fileName.substring(fileName.lastIndexOf(".")+1);//获得excel文件后缀

			//判断格式是否符合要求
			if(fileType.equalsIgnoreCase("xls")||fileType.equalsIgnoreCase("xlsx")){
				System.out.println("文件原名: " + fileName);
				System.out.println("文件名称: " + excelFile.getName());
				System.out.println("文件长度: " + excelFile.getSize()/1024+" Kb");
				System.out.println("文件类型: " + excelFile.getContentType());
				System.out.println("========================================");
				int excelType=-1;
				if(fileType.equalsIgnoreCase("xls")){
					excelType=0;
				}else{
					excelType=1;
				}
				try {
					InputStream stream=excelFile.getInputStream();
					res=webService.loadExcelToList(stream,excelType);
					request.setAttribute("res",res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					res.setSuccess(false);
					res.setMessage("读取excel文件io流异常");
				}
			}else{
				res.setSuccess(false);
				res.setMessage("excel格式错误！请按照要求上传xls,xlsx为后缀的excel文件！");
			}


		}
		this.res=res;
		//查询必要参数返回、
		//查询员工并返回，需要id,employee;
		//查询客户单位
		List<Customer> customerList =webService.findAllCustomerList();
		List<Employee> emplist = webService.findEmployeeList();
		request.setAttribute("customerList", customerList);
		request.setAttribute("empList", emplist);
		return "admin/editAddPlan";
	}


	/**
	 * 从session中取出存储的excel数据展示
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/showTableDataExcelHandler.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<Plan, String> showTableDataExcelHandler(Result<Plan, String> rs,HttpServletRequest  request, HttpServletResponse response) throws UnsupportedEncodingException{
		/*String param =request.getParameter("rs");
		Gson gson = new Gson();
		rs=gson.fromJson(param, rs.getClass());*/
		return this.res;
	}


	/**
	 * 按照客户id查找客户部门集合并返回
	 * @param customerId
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/findDeparmentListByCustomerId.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<SelectResult, String> findDeparmentListByCustomerId(Integer selectId,HttpServletRequest  request, HttpServletResponse response) throws UnsupportedEncodingException{
		Result<SelectResult, String> res = new Result<>();
		if(selectId!=null){
			List<CustomerDepartment> list = webService.findDeparmentListByCustomerId(selectId);
			List<SelectResult> selectList = new ArrayList<SelectResult>();
			SelectResult sr;
			for(CustomerDepartment dep:list){
				sr = new SelectResult();
				sr.setId(dep.getId());
				sr.setText(dep.getDepartmentName());
				selectList.add(sr);
			}
			res.setSuccess(true);
			res.setMessage("load success");
			res.setAaData(selectList);
		}
		return res;
	}

	/**
	 * 按照客户部门id查找对应的客户联系人列表并返回
	 * @param selectId
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/findContactsListByDepId.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<SelectResult, String> findContactsListByDepId(Integer selectId,HttpServletRequest  request, HttpServletResponse response) throws UnsupportedEncodingException{
		Result<SelectResult, String> res = new Result<>();
		if(selectId!=null){
			List<SelectResult> list = webService.findContactsListByDepId(selectId);
			res.setSuccess(true);
			res.setMessage("load success");
			res.setAaData(list);
		}
		return res;
	}

	/**
	 * 插入导入计划方法
	 * @param selectId
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/insertPlan.htm",method={RequestMethod.POST})
	@ResponseBody
	public Result<String, String> insertPlan(String planListStr,HttpServletRequest  request, HttpServletResponse response) throws UnsupportedEncodingException{
		Result<String, String> res = new Result<>();
		List<Plan> planList = new ArrayList<>();
		Gson gson = new Gson();
		planList = gson.fromJson(planListStr, new TypeToken<List<Plan>>(){}.getType());
		res = checkParams(planList);
		if(res.isSuccess()){
			res=webService.checkAddPlanList(planList);
			if(res.isSuccess()){
				res = webService.savePlanList(planList);
			}
		}
		return res;
	}

	private Result<String, String> checkParams(List<Plan> planList) {
		// TODO Auto-generated method stub
		Result<String, String> res = new Result<String, String>();
		String errorCode ="参数效验错误";
		res.setSuccess(false);
		res.setMessage(errorCode);
		int i =0;int line =0;
		try {
			if(planList!=null&&planList.size()>0){
				Plan plan = null;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				int length = planList.size();
				for(;i<length;i++){
					line = i+1;
					plan = planList.get(i);
					//日期
					if(plan.getOrderDate()==null){
						res.setMessage("第"+line+"行订单时间不能为空");
						break;
					}else{
						sdf.setLenient(false);
						sdf.parse(plan.getOrderDate());
					}
					//商品名称
					if(plan.getGoodsName()==null||"".equals(plan.getGoodsName().trim())){
						res.setMessage("第"+line+"行商品名称不能为空");
						break;
					}
					//商品规格
					if(plan.getGoodsType()==null||"".equals(plan.getGoodsType())){
						res.setMessage("第"+line+"行商品规格不能为空");
						break;
					}
					//商品单位
					if(StringUtils.isEmpty(plan.getGoodsUnit())){
						res.setMessage("第"+line+"行商品单位不能为空");
						break;
					}
					//商品数量
					if(plan.getGoodsNum()==null){
						res.setMessage("第"+line+"行商品数量不能为空");
						break;
					}
					if(plan.getGoodsNum()<=0){
						res.setMessage("第"+line+"行商品数量不能为小于等于0的数字");
						break;
					}
					//客户单位
					if(StringUtils.isEmpty(plan.getPlanUnit())){
						res.setMessage("第"+line+"行客户单位不能为空");
						break;
					}
					
					//客户部门
					if(StringUtils.isEmpty(plan.getDeparmentName())){
						res.setMessage("第"+line+"行客户部门不能为空");
						break;
					}
					//客户使用人
					if(StringUtils.isEmpty(plan.getContactsName())){
						res.setMessage("第"+line+"行客户使用人不能为空");
						break;
					}
					//操作人
					if(StringUtils.isEmpty(plan.getEmployeeName())){
						res.setMessage("第"+line+"行客户操作人不能为空");
						break;
					}
					
					if(line==length){
						res.setSuccess(true);
						res.setMessage("基本验证成功");
					}

				}
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			log.error("text format类型转换错误",e);
			res.setMessage("第"+line+"行订单时间格式有误");
		} catch(Exception e){
			log.error("参数验证错误",e);
			res.setMessage("参数验证错误");
		}

		return res;
	}

}
